import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getCartCount, getCartList } from '@/api/cart'

export const useCartStore = defineStore('cart', () => {
  // 状态
  const cartCount = ref(0)
  const cartList = ref([])
  const selectedItems = ref([])

  // 计算属性
  const totalAmount = computed(() => {
    return selectedItems.value.reduce((total, item) => {
      return total + item.price * item.quantity
    }, 0)
  })

  const totalQuantity = computed(() => {
    return selectedItems.value.reduce((total, item) => {
      return total + item.quantity
    }, 0)
  })

  // 方法
  async function updateCartCount() {
    try {
      const res = await getCartCount()
      cartCount.value = res.data
    } catch (error) {
      console.error('获取购物车数量失败:', error)
    }
  }

  async function loadCartList() {
    try {
      const res = await getCartList()
      cartList.value = res.data
      // 默认选中所有商品
      selectedItems.value = [...cartList.value]
    } catch (error) {
      console.error('获取购物车列表失败:', error)
      throw error
    }
  }

  function updateSelectedItems(items) {
    selectedItems.value = items
  }

  function clearCart() {
    cartCount.value = 0
    cartList.value = []
    selectedItems.value = []
  }

  return {
    // 状态
    cartCount,
    cartList,
    selectedItems,
    // 计算属性
    totalAmount,
    totalQuantity,
    // 方法
    updateCartCount,
    loadCartList,
    updateSelectedItems,
    clearCart
  }
}) 